package com.group7d.repository;

import com.group7d.entity.TestResult;
import com.group7d.util.SystemConfig;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * 数据库工具.
 *
 * @author jinshulin (jinshulin170531@credithc.com)
 * @version 0.0.1-SNAPSHOT
 * @since 2018年05月02日 22时50分
 */
public class DBUtils {

    private static final String COLUMNS =
        "\"ctime\", \"elapsed\", \"label\", \"response_code\", " +
            "\"response_msg\", \"thread_name\", \"data_type\", \"success\", " +
            "\"failure_msg\", \"bytes\", \"sent_bytes\", \"grp_threads\", \"all_threads\", " +
            "\"latency\", \"idle_time\", \"connect\"";

    private static final String INSERT_SQL =
        String.format("INSERT INTO jmeter_test_result(%s), VALUES " +
            "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", COLUMNS);

    public static void init() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void saveAll(List<TestResult> list) {
        init();
        try (Connection conn = SystemConfig.getConnection()) {
            conn.setAutoCommit(false);
            PreparedStatement pst = conn.prepareStatement(INSERT_SQL);
            list.forEach(result -> {
                try {
                    pst.setLong(1, result.getTimeStamp());
                    pst.setString(2, result.getElapsed());
                    pst.setString(3, result.getLabel());
                    pst.setString(4, result.getResponseCode());
                    pst.setString(5, result.getResponseMessage());
                    pst.setString(6, result.getThreadName());
                    pst.setString(7, result.getDataType());
                    pst.setString(8, result.getSuccess());
                    pst.setString(9, result.getFailureMessage());
                    pst.setLong(10, result.getBytes());
                    pst.setLong(11, result.getSentBytes());
                    pst.setInt(12, result.getGrpThreads());
                    pst.setInt(13, result.getAllThreads());
                    pst.setString(14, result.getLatency());
                    pst.setString(15, result.getIdleTime());
                    pst.setString(16, result.getConnect());
                    pst.addBatch();
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
            });
            pst.executeBatch();
            conn.commit();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
